
// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import NECommonKit
import NIMSDK
import UIKit
import NEChatUIKit


@objc public protocol TeamAnnouncementDelegate: NSObjectProtocol {
    /// 群公告变更
    func updateTeamAnnouncement(announcement: String?, serverExtension: String?)
}

@objcMembers
open class NEBaseTeamAnnouncementViewController: NEBaseViewController, TeamAnnouncementDelegate {
    
    public var team: V2NIMTeam?
    public var showServerExtension: String?
    public var showAnnouncement: String?

    public let infoBackView = UIView()
    public let contentBackView = UIView()
    
    public let viewModel = TeamAnnouncementViewModel()
    
    public lazy var headerView: NEUserHeaderView = {
        let header = NEUserHeaderView(frame: .zero)
        header.titleLabel.font = NEConstant.defaultTextFont(14)
        header.titleLabel.textColor = UIColor.white
        header.layer.cornerRadius = 6
        header.clipsToBounds = true
        header.translatesAutoresizingMaskIntoConstraints = false
        return header
    }()
    
    public lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NEConstant.defaultTextFont(16.0)
        label.textColor = .normalTeamTitleColor
        label.accessibilityIdentifier = "id.userName"
        return label
    }()
    
    public lazy var roleLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NEConstant.defaultTextFont(13.0)
        label.textColor = .normalTeamSubTitleColor
        label.accessibilityIdentifier = "id.role"
        return label
    }()
    
    public lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NEConstant.defaultTextFont(13.0)
        label.textColor = .normalTeamSubTitleColor
        label.accessibilityIdentifier = "id.time"
        label.textAlignment = .right
        return label
    }()
    
    /// 公告输入框
    public lazy var contentLabel: UITextView = {
        let label = NEChatTextView()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.isEditable = false
        label.isSelectable = false
        label.isScrollEnabled = true
        label.textContainerInset = .zero
        label.contentInset = .zero
        label.textContainer.lineFragmentPadding = 0.0
        label.isUserInteractionEnabled = true
        label.font = NEConstant.defaultTextFont(14.0)
        label.backgroundColor = .clear
        label.accessibilityIdentifier = "id.announcement"
        return label
    }()
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        weak var weakSelf = self
        viewModel.getCurrentMember(team?.teamId) { member, error in
            if let err = error {
                weakSelf?.view.makeToast(err.localizedDescription)
            }
            weakSelf?.setupUI()
        }
    }
    
    /// 布局初始化
    open func setupUI() {
        navigationView.setMoreButtonTitle(localizable("edit"))
        navigationView.moreButton.titleLabel?.font = NEConstant.defaultTextFont(14)
        navigationView.addMoreButtonTarget(target: self, selector: #selector(editAnnouncement))
        if let serverExtension = team?.serverExtension, serverExtension.contains(discussTeamKey) {
            title = localizable("discuss_announcement")
        } else {
            title = localizable("team_announcement")
        }
        
        infoBackView.backgroundColor = .white
        infoBackView.translatesAutoresizingMaskIntoConstraints = false
        infoBackView.clipsToBounds = false
        view.addSubview(infoBackView)
        
        infoBackView.addSubview(headerView)
        infoBackView.addSubview(nameLabel)
        infoBackView.addSubview(roleLabel)
        infoBackView.addSubview(timeLabel)
        
        weak var weakSelf = self

        TeamHelper.announcemenUserInfo(team?.teamId, team?.serverExtension, { user in
            if let user = user {
                if let url = user.member?.nimUser?.user?.avatar, !url.isEmpty {
                    weakSelf?.headerView.sd_setImage(with: URL(string: url), completed: nil)
                    weakSelf?.headerView.setTitle("")
                } else {
                    weakSelf?.headerView.image = nil
                    weakSelf?.headerView.setTitle(user.member?.showNickInTeam() ?? "")
                    weakSelf?.headerView.backgroundColor = UIColor.colorWithString(string: user.member?.nimUser?.user?.accountId)
                }
                weakSelf?.nameLabel.text = user.member?.atNameInTeam()
                weakSelf?.roleLabel.text = TeamHelper.userTitleName(user.member)
                weakSelf?.timeLabel.text = "发布时间：\(user.time ?? "")"
            }
        })
        
        
        contentBackView.backgroundColor = .white
        contentBackView.translatesAutoresizingMaskIntoConstraints = false
        contentBackView.clipsToBounds = false
        
        view.addSubview(contentBackView)
        view.sendSubviewToBack(contentBackView)
        
        showServerExtension = team?.serverExtension
        showAnnouncement = team?.announcement
        
        contentBackView.addSubview(contentLabel)
        
        if let announcement = showAnnouncement, !announcement.isEmpty {
            contentLabel.text = announcement
        } else {
            contentLabel.text = "暂无公告"
        }

        if getPermission() == false {
            rightNavButton.isHidden = true
            navigationView.moreButton.isHidden = true
        }
    }
    
    open func reloadUI(){}
    
    /// 权限改变
    func getPermission() -> Bool {
        if let member = viewModel.userInTeam,TeamHelper.canEditAnnouncement(member) {
            return true
        }
//        if let ownerId = team?.ownerAccountId, IMKitClient.instance.isMe(ownerId) {
//            return true
//        }
//        if let mode = team?.updateInfoMode, mode == .TEAM_UPDATE_INFO_MODE_ALL {
//            return true
//        }
//        if let member = viewModel.currentTeamMember, member.memberRole == .TEAM_MEMBER_ROLE_MANAGER {
//            return true
//        }
        return false
    }
    
    /// 编辑公告
    func editAnnouncement() {
        
    }
    
    public func updateTeamAnnouncement(announcement: String?, serverExtension: String?) {
        if let announcement = announcement {
            showAnnouncement = announcement
            showServerExtension = serverExtension
            contentLabel.text = announcement.isEmpty ? "暂无公告" : announcement

            weak var weakSelf = self
            TeamHelper.announcemenUserInfo(team?.teamId, serverExtension, { user in
                if let user = user {
                    if let url = user.member?.nimUser?.user?.avatar, !url.isEmpty {
                        weakSelf?.headerView.sd_setImage(with: URL(string: url), completed: nil)
                        weakSelf?.headerView.setTitle("")
                    } else {
                        weakSelf?.headerView.image = nil
                        weakSelf?.headerView.setTitle(user.member?.showNickInTeam() ?? "")
                        weakSelf?.headerView.backgroundColor = UIColor.colorWithString(string: user.member?.nimUser?.user?.accountId)
                    }
                    weakSelf?.nameLabel.text = user.member?.atNameInTeam()
                    weakSelf?.roleLabel.text = TeamHelper.userTitleName(user.member)
                    weakSelf?.timeLabel.text = "发布时间：\(user.time ?? "")"
                    
                    weakSelf?.infoBackView.isHidden = false
                    
                    weakSelf?.reloadUI()
                }
            })
        }        
    }
}
